import os
import time
from datetime import datetime

import exifread
from PIL import Image


def get_heic_photo_date_taken(file_path):
    with open(file_path, 'rb') as image_file:
        exif_tags = exifread.process_file(image_file)
    if 'EXIF DateTimeOriginal' in exif_tags:
        return exif_tags['EXIF DateTimeOriginal']
    else:
        return None

def move_photos(source_dir):
    for root, dirs, files in os.walk(source_dir):
        for file in files:
            file_path = os.path.join(root, file)
            if file.endswith(('.HEIC', '.heic')):  # 假设的 EHIC 文件扩展名
                # 获取图片的拍摄时间
                date_taken = get_heic_photo_date_taken(file_path)
                if date_taken:
                    # 解析日期时间字符串
                    year = time.strftime("%Y", time.strptime(
                        date_taken.values, "%Y:%m:%d %H:%M:%S"))
                    # 创建对应年份的文件夹
                    target_dir = os.path.join(source_dir , f"{year}年")
                    if not os.path.exists(target_dir):
                        os.makedirs(target_dir)
                    # 移动文件
                    os.rename(file_path, os.path.join(target_dir, file))


# 指定目录
source_dir = "F:\\糖宝照片\\2019年"
move_photos(source_dir)
